<template>
  <van-loading v-if="isLoading" type="spinner" />
  <van-icon
    v-else
    :color="value ? '#5094f3' : '#777'"
    :name="value ? 'star' : 'star-o'"
    @click="collectHandler"
  />
</template>
<script>
import { addArticleCollectApi, delArticleCollectApi } from "@/api/Article";
export default {
  name: "CollectArticle",
  props: {
    // 接收收藏的状态
    value: {
      type: Boolean,
      required: true,
    },
    // 文章ID
    articleId: {
      type: [Number, String],
      required: true,
    },
  },
  data() {
    return {
      isLoading: false,
    };
  },
  methods: {
    async collectHandler() {
      // 判断是否登录
      if (!this.$store.getters.token) return this.$toast.fail("请登录");
      // 已登录了
      this.isLoading = true;
      try {
        if (this.value) {
          // 已收藏，要取消
          await delArticleCollectApi(this.articleId);
        } else {
          // 未收藏，则收藏
          await addArticleCollectApi({
            target: this.articleId,
          });
        }
        // 提示成功
        this.$toast.success(this.value ? "取消成功" : "收藏成功");

        // 视图的更新
        this.$emit("input", !this.value);
      } catch (error) {
        this.$toast.fail("操作失败");
        console.log(error);
      }
      this.isLoading = false;
    },
  },
};
</script>
<style></style>
